#!/bin/bash
#
# gelatin-nv8.sh
# Author: Andy Chu
#
# Run gelatin under narwhal-v8


MODULE=$1
TARGET=${TARGET:-node}
INTERPRETER=${INTERPRETER:-./nw.sh}

NARWHAL_ROOT=/home/andy/git/mynarwhal
GELATIN_ROOT="$NARWHAL_ROOT/packages/gelatin-js"

EXECUTABLE="${EXECUTABLE:-$GELATIN_ROOT/bin/gelatin}"

# TODO: Run embed-tree on other engines
./nw.sh $NARWHAL_ROOT/packages/oil/bin/embed-tree $PWD/data/archive.jsont 2> $PWD/__embedded.js
if [ $? -ne 0 ]; then
  echo 'Embedding failed'
  exit 1
fi


# Bootstrapping issues: remove system and file

OUTPUT="${OUTPUT:-$GELATIN_ROOT/$MODULE-$TARGET.js}"

INCLUDES="$PWD/__embedded.js"
INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/dummy-module.js"
INCLUDES="$INCLUDES,$NARWHAL_ROOT/engines/default/lib/object.js"
INCLUDES="$INCLUDES,$NARWHAL_ROOT/engines/default/lib/array.js"

if [ "$TARGET" == 'node' ]; then
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/dummy-system.js"
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/node-print.js"
  SHEBANG='/usr/bin/node'
  MAIN="$GELATIN_ROOT/data/node-main.jsont"
  EXCLUDES='system,file'
  RUNTIME='sys,posix'
elif [ "$TARGET" == 'wsh' ]; then
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/dummy-system.js"
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/dummy-require.js"
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/wsh-print.js"
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/Array_indexOf.js"
  INCLUDES="$INCLUDES,$GELATIN_ROOT/runtime/wsh-term.js"
  MAIN="$GELATIN_ROOT/data/wsh-main.jsont"
  EXCLUDES='system,file,term'
else
  SHEBANG='/usr/bin/env narwhal'
  MAIN="$GELATIN_ROOT/data/narwhal-main.jsont"
  EXCLUDES=''
  RUNTIME='system,file'
fi

$INTERPRETER $EXECUTABLE \
  -o "$OUTPUT" \
  -d "$NARWHAL_ROOT/packages/" \
  -p "$NARWHAL_ROOT" \
  -i "$INCLUDES" \
  -x "$EXCLUDES" \
  -r "$RUNTIME" \
  -m "$MAIN" \
  -s "$SHEBANG" \
  -e "$TARGET" \
  $MODULE
